const { Transform } = require('stream');
const _ = require('lodash');
const moment = require('moment');
const utils = require('../../utils');

module.exports = function (list, hasOldName = false) {
  const stream = new Transform({ objectMode: true });

  stream._transform = async function (chunk = '', encoding, callback) {
    utils.debug('fieldTransform [chunk]:', chunk);
    let obj = hasOldName ? { ...chunk } : {};
    for (let o of list) {
      if (_.isArray(o)) {
        const p = (o[0] || '').split('->');
        o = { name: p[0], newName: p[1], value: o[1] };
      }
      if (_.isString(o)) {
        obj[o] = chunk[o];
      } else {
        let newValue = o.name === '$' ? chunk : chunk[o.name];
        if (o.value) {
          let func = o.value;
          func = utils.parseFunction(func);
          newValue = _.isFunction(func) ? await func(newValue, { _, moment, utils, $$: chunk }) : func;
        }
        if (o.newName === '$') {
          obj = newValue;
        } else {
          obj[o.newName || o.name] = newValue;
        }
      }
    }
    stream.push(obj);
    callback();
  };

  stream.on('finish', function () {
    utils.debug('fieldTransform [finish]');
  });

  return stream;
};
